package cn.lhn.ridersclub.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EncryptUtil {

    /**
     * 对称加解密，用于数据信息脱敏存储
     */
    public static class AES {

        private static final String KEY_ALGORITHM = "AES";
        private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";  //默认的加密算法

        /**
         * AES 加密操作
         */
        public static String encrypt(String data, String key) {
            try {
                Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);   // 创建密码器

                byte[] byteContent = data.getBytes(StandardCharsets.UTF_8);

                cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));   // 初始化为加密模式的密码器

                byte[] result = cipher.doFinal(byteContent);    // 加密

                return Base64Utils.encodeToString(result);  //通过Base64转码返回
            } catch (Exception ex) {
                Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
            }

            return null;
        }

        /**
         * AES 解密操作
         */
        public static String decrypt(String content, String key) {

            try {
                //实例化
                Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

                //使用密钥初始化，设置为解密模式
                cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));

                //执行操作
                byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
                return new String(result, StandardCharsets.UTF_8);
            } catch (Exception ex) {
                ex.printStackTrace();
                Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
            }

            return null;
        }

        /**
         * 生成加密秘钥
         */
        private static SecretKeySpec getSecretKey(String password) {
            //返回生成指定算法密钥生成器的 KeyGenerator 对象
            KeyGenerator kg;
            try {
                kg = KeyGenerator.getInstance(KEY_ALGORITHM);
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(password.getBytes());
                //AES 要求密钥长度为 128
                kg.init(128, random);
                //生成一个密钥
                SecretKey secretKey = kg.generateKey();
                return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
    }

    /**
     * 非对称加解密，用户数据信息脱敏传输
     */
    public static class RSA {
        public static final String KEY_ALGORITHM = "RSA";
        public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

        private static final String PUBLIC_KEY = "RSAPublicKey";
        private static final String PRIVATE_KEY = "RSAPrivateKey";

        public static byte[] decryptBASE64(String key) {
            return Base64.decodeBase64(key);
        }

        public static String encryptBASE64(byte[] bytes) {
            return Base64.encodeBase64String(bytes);
        }

        /**
         * 用私钥对信息生成数字签名
         */
        public static String sign(byte[] data, String privateKey) throws Exception {
            // 解密由base64编码的私钥
            byte[] keyBytes = decryptBASE64(privateKey);
            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            // 取私钥匙对象
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 用私钥对信息生成数字签名
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            signature.update(data);
            return encryptBASE64(signature.sign());
        }

        public static PrivateKey strToPrivateKey(String privateKey) throws Exception {
            // 解密由base64编码的私钥
            byte[] keyBytes = decryptBASE64(privateKey);
            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            // 取私钥匙对象
            return keyFactory.generatePrivate(pkcs8KeySpec);
        }

        /**
         * 校验数字签名
         */
        public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
            // 解密由base64编码的公钥
            byte[] keyBytes = decryptBASE64(publicKey);
            // 构造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            // 取公钥匙对象
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(data);
            // 验证签名是否正常
            return signature.verify(decryptBASE64(sign));
        }

        public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
            // 对密钥解密
            byte[] keyBytes = decryptBASE64(key);
            // 取得私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }

        /**
         * 用私钥解密
         */
        public static byte[] privateKeyDecrypt(String data, String key) throws Exception {
            return decryptByPrivateKey(decryptBASE64(data),key);
        }

        /**
         * 用公钥解密
         */
        public static byte[] publicKeyDecrypt(byte[] data, String key)
                throws Exception {
            // 对密钥解密
            byte[] keyBytes = decryptBASE64(key);
            // 取得公钥
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);
            // 对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }

        /**
         * 用公钥加密
         */
        public static byte[] publicKeyEncrypt(String data, String key)
                throws Exception {
            // 对公钥解密
            byte[] keyBytes = decryptBASE64(key);
            // 取得公钥
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data.getBytes());
        }

        /**
         * 用私钥加密
         */
        public static byte[] privateKeyEncrypt(byte[] data, String key)
                throws Exception {
            // 对密钥解密
            byte[] keyBytes = decryptBASE64(key);
            // 取得私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }

        /**
         * 取得私钥
         */
        public static String getPrivateKey(Map<String, Key> keyMap)
                throws Exception {
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            return encryptBASE64(key.getEncoded());
        }

        /**
         * 取得公钥
         */
        public static String getPublicKey(Map<String, Key> keyMap)
                throws Exception {
            Key key = keyMap.get(PUBLIC_KEY);
            return encryptBASE64(key.getEncoded());
        }

        /**
         * 初始化密钥
         */
        public static Map<String, Key> initKey() throws NoSuchAlgorithmException {
            KeyPairGenerator keyPairGen = KeyPairGenerator
                    .getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            Map<String, Key> keyMap = new HashMap<>(2);


            keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
            keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
            return keyMap;
        }

    }

    public static class MD5 {

        private final static char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();

        public static String encrypt(String data) {
            return DigestUtils.md5Hex(data);
        }

        public static String encrypt(String data, String salt) {
            return DigestUtils.md5Hex(data + salt);
        }

        //  获取随机盐
        public static String getSalt(int n) {

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                char aChar = chars[new Random().nextInt(chars.length)];
                sb.append(aChar);
            }
            return sb.toString();
        }
    }

}
